# -*- coding:utf-8 -*-
import xlrd
import xlwt
from pyExcelerator import *
from xlutils.copy import copy
from openpyxl import load_workbook
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8') 
filecs="HexArray.cs"
filenamecs= open(filecs,'a')

def hex2arr( hexfile1): 
    if(hexfile1 != ""):   
        hex1= open(hexfile1,'r')
    
    seg_no = 0
    flashAddr = [0x08008000]   
    FileSize = [0xF8000]
    flash_checksum = [0]
    print>>filenamecs, "namespace WinCANTool"
    print>>filenamecs, "{"
    print>>filenamecs, "    public partial class FlashWindow1319"  
    print>>filenamecs, "    {"    
    print>>filenamecs, "        public byte[][] SegData;"
    print>>filenamecs, "        public int[] FileSize;"   
    print>>filenamecs, "        public int[] flashAddr;" 
    print>>filenamecs, "        public ushort[] flash_checksum;" 
    print>>filenamecs, "        public void InitSegData(  )" 
    print>>filenamecs, "        {"
    print>>filenamecs, "            FileSize = new int[1];"
    print>>filenamecs, "            FileSize[0] = 0xF8000;"
    
    print>>filenamecs, "            flash_checksum = new ushort[1];"
    
    print>>filenamecs, "            flashAddr = new int[1];"
    print>>filenamecs, "            flashAddr[0] = 0x08008000;"

    
    print>>filenamecs, "            SegData = new byte[1][];"

    print>>filenamecs, "            SegData[%d] = new byte[0x%x]" %(seg_no, FileSize[seg_no])
    print>>filenamecs, "            {"      

    for LineData in hex1:

        index = 1
        len = int(LineData[index:index+2],16)
        
        index += 2
        addr = int(LineData[index:index+4],16)
        
        index += 4
        section = int(LineData[index:index+2],16)
        
        index += 2
        
        if (section == 0x00):
            hex_data = ''
            for l in range(0, len):
                hex_data += "0x" +LineData[index:index+2]+','
                flash_checksum[seg_no] += int(LineData[index:index+2],16);
                #FileSize[seg_no] += 1
                index += 2
                
            print>>filenamecs, "                %s"       % (hex_data)                  
             
    print>>filenamecs, "            }; // seg_no=%d, startaddr=0x%x, size=0x%x" % (seg_no, flashAddr[seg_no], FileSize[seg_no])  



    for i in range(0,1):
        print>>filenamecs, "            flash_checksum[%d] = 0x%x;" %(i, flash_checksum[i] & 0xffff)
    
    print>>filenamecs, "        }"

    print>>filenamecs, "    }"
    print>>filenamecs, "}"
if __name__ == '__main__':

    filenamecs= open(filecs,'w')
    filenamecs = open(filecs,'a');    
    hex2arr("391420125669.hex")


    
    
    
